const resolve = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')
const json = require('@rollup/plugin-json')
const autoprefixer = require('autoprefixer')
const postcss = require('rollup-plugin-postcss')
const copy = require('rollup-plugin-copy')
const run = require('@rollup/plugin-run')
const di = require('@rollup/plugin-dynamic-import-vars')

const dev = process.env.NODE_ENV !== 'production'

// 拷贝以下目录下的jsx文件至dist对应目录
const files = ['', 'user/']
const serverTargets = () =>
  files.map((f) => ({
    src: `src/server/views/${f}*.html`,
    dest: `dist/server/views/${f}`,
  }))
const serverEjsTargets = () =>
  files.map((f) => ({
    src: `src/server/views/${f}*.ejs`,
    dest: `dist/server/views/${f}`,
  }))
const socketTargets = () =>
  files.map((f) => ({
    src: `src/socket/views/${f}*.html`,
    dest: `dist/socket/views/${f}`,
  }))

const targets = [...serverTargets(), ...serverEjsTargets(), ...socketTargets()]

module.exports = {
  input: 'src/app.js',
  output: {
    dir: 'dist',
    format: 'cjs',
    exports: 'named', // 指定导出模式（自动、默认、命名、无）
    preserveModules: true, // 保留模块结构
    preserveModulesRoot: 'src', // 将保留的模块放在根级别的此路径下
  },
  external: (id) => id.indexOf('node_modules') !== -1,
  plugins: [
    resolve(),
    commonjs(),
    json(),
    copy({ targets }),
    postcss({
      plugins: [autoprefixer()],
    }),
    di(),
    dev && run(),
  ],
  watch: {
    clearScreen: false,
  },
}
